package com.artisan.view;

import java.awt.EventQueue;

import javax.swing.JInternalFrame;
import javax.swing.ImageIcon;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Font;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.artisan.dao.ClassDao;
import com.artisan.dao.CourseDao;
import com.artisan.dao.TeacherDao;
import com.artisan.model.Course;
import com.artisan.model.SelectedCourse;
import com.artisan.model.Student;
import com.artisan.model.StudentClass;
import com.artisan.model.Teacher;
import com.artisan.util.StringUtil;

import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ManageCourseFrm extends JInternalFrame {
	private JTextField searchCourseNameTextField;
	private JTable courseListTable;
	private JTextField editCourseTextField;
	private JTextField editCourseStudentNumTextField;
	private JComboBox editCourseTeachComboBox;
	private JTextArea editCourseInfoTextArea;
	private JComboBox searchTeacherComboBox;
	private JButton deleteCourseButton;
	private List<Teacher> teacherList = new ArrayList<Teacher>();

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ManageCourseFrm frame = new ManageCourseFrm();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ManageCourseFrm() {
		setClosable(true);
		setIconifiable(true);

		getContentPane().setFont(new Font("微软雅黑", Font.PLAIN, 14));
		setTitle("课程信息管理");
		setFrameIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/课程.png")));
		setBounds(100, 100, 978, 715);

		JLabel lblNewLabel = new JLabel("课程名称:");
		lblNewLabel.setIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/课程.png")));
		lblNewLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		searchCourseNameTextField = new JTextField();
		searchCourseNameTextField.setColumns(10);

		JLabel lblNewLabel_1 = new JLabel("授课教师:");
		lblNewLabel_1.setIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/老师.png")));
		lblNewLabel_1.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		searchTeacherComboBox = new JComboBox();

		JButton searchButton = new JButton("查询");
		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				searchCourse(ae);
			}
		});
		searchButton.setIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/搜索.png")));
		searchButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		JScrollPane scrollPane = new JScrollPane();

		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(
				new EtchedBorder(EtchedBorder.LOWERED, new Color(255, 255, 255), new Color(160, 160, 160)),
				"\u7F16\u8F91\u8BFE\u7A0B\u4FE1\u606F", TitledBorder.LEADING, TitledBorder.TOP, null,
				new Color(0, 0, 0)));
		GroupLayout groupLayout = new GroupLayout(getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
				.addGroup(groupLayout.createSequentialGroup().addGap(106)
						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 747, Short.MAX_VALUE)
								.addComponent(panel, GroupLayout.DEFAULT_SIZE, 747, Short.MAX_VALUE)
								.addGroup(groupLayout.createSequentialGroup().addComponent(lblNewLabel).addGap(18)
										.addComponent(searchCourseNameTextField, GroupLayout.PREFERRED_SIZE, 155,
												GroupLayout.PREFERRED_SIZE)
										.addGap(58).addComponent(lblNewLabel_1).addGap(18)
										.addComponent(searchTeacherComboBox, GroupLayout.PREFERRED_SIZE, 162,
												GroupLayout.PREFERRED_SIZE)
										.addGap(77).addComponent(searchButton, GroupLayout.PREFERRED_SIZE, 97,
												GroupLayout.PREFERRED_SIZE)))
						.addGap(119)));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup().addGap(41)
						.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblNewLabel)
								.addComponent(searchCourseNameTextField, GroupLayout.PREFERRED_SIZE, 35,
										GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNewLabel_1)
								.addComponent(searchTeacherComboBox, GroupLayout.PREFERRED_SIZE,
										GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(searchButton, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE))
						.addGap(18)
						.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 316, GroupLayout.PREFERRED_SIZE)
						.addGap(18).addComponent(panel, GroupLayout.PREFERRED_SIZE, 229, GroupLayout.PREFERRED_SIZE)
						.addContainerGap(23, Short.MAX_VALUE)));

		JLabel lblNewLabel_2 = new JLabel("课程名称:");
		lblNewLabel_2.setIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/课程.png")));
		lblNewLabel_2.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		editCourseTextField = new JTextField();
		editCourseTextField.setColumns(10);

		JLabel lblNewLabel_3 = new JLabel("授课教师:");
		lblNewLabel_3.setIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/老师.png")));
		lblNewLabel_3.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		editCourseTeachComboBox = new JComboBox();

		JLabel lblNewLabel_4 = new JLabel("学生人数:");
		lblNewLabel_4.setIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/人数.png")));
		lblNewLabel_4.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		editCourseStudentNumTextField = new JTextField();
		editCourseStudentNumTextField.setColumns(10);

		JLabel lblNewLabel_5 = new JLabel("课程介绍:");
		lblNewLabel_5.setIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/介绍.png")));
		lblNewLabel_5.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		editCourseInfoTextArea = new JTextArea();

		JButton submitEditButton = new JButton("确认修改");
		submitEditButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				editCourseSubmit(ae);
			}
		});
		submitEditButton.setIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/确认.png")));
		submitEditButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));

		deleteCourseButton = new JButton("删除课程");
		deleteCourseButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent ae) {
				deleteCourse(ae);
			}
		});
		deleteCourseButton.setIcon(new ImageIcon(ManageCourseFrm.class.getResource("/com/artisan/image/删除.png")));
		deleteCourseButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel
				.createSequentialGroup()
				.addGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel.createSequentialGroup()
						.addContainerGap()
						.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panel.createSequentialGroup().addComponent(lblNewLabel_2).addGap(18)
										.addComponent(editCourseTextField, GroupLayout.PREFERRED_SIZE, 152,
												GroupLayout.PREFERRED_SIZE))
								.addGroup(gl_panel.createSequentialGroup()
										.addComponent(lblNewLabel_4, GroupLayout.DEFAULT_SIZE, 81, Short.MAX_VALUE)
										.addGap(18).addComponent(editCourseStudentNumTextField,
												GroupLayout.PREFERRED_SIZE, 152, GroupLayout.PREFERRED_SIZE)))
						.addGap(34)
						.addGroup(gl_panel.createParallelGroup(Alignment.LEADING, false)
								.addComponent(lblNewLabel_5, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)
								.addComponent(lblNewLabel_3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE))
						.addGap(18))
						.addGroup(gl_panel.createSequentialGroup().addGap(124)
								.addGroup(gl_panel.createParallelGroup(Alignment.LEADING, false)
										.addComponent(deleteCourseButton, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE,
												GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(submitEditButton, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE,
												GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
								.addGap(159)))
				.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addComponent(editCourseInfoTextArea, GroupLayout.PREFERRED_SIZE, 283,
								GroupLayout.PREFERRED_SIZE)
						.addComponent(editCourseTeachComboBox, GroupLayout.PREFERRED_SIZE, 143,
								GroupLayout.PREFERRED_SIZE))
				.addContainerGap(58, Short.MAX_VALUE)));
		gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel
				.createSequentialGroup().addContainerGap()
				.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE).addComponent(lblNewLabel_2)
						.addComponent(editCourseTextField, GroupLayout.PREFERRED_SIZE, 32, GroupLayout.PREFERRED_SIZE)
						.addComponent(
								lblNewLabel_3)
						.addComponent(editCourseTeachComboBox, GroupLayout.PREFERRED_SIZE, 29,
								GroupLayout.PREFERRED_SIZE))
				.addGap(18)
				.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(editCourseInfoTextArea, GroupLayout.PREFERRED_SIZE, 124,
								GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_panel.createSequentialGroup().addGroup(gl_panel
								.createParallelGroup(Alignment.LEADING).addComponent(lblNewLabel_4)
								.addGroup(gl_panel.createSequentialGroup()
										.addComponent(editCourseStudentNumTextField, GroupLayout.PREFERRED_SIZE, 30,
												GroupLayout.PREFERRED_SIZE)
										.addGap(17).addComponent(submitEditButton))
								.addComponent(lblNewLabel_5)).addGap(20).addComponent(deleteCourseButton)))
				.addContainerGap(22, Short.MAX_VALUE)));
		panel.setLayout(gl_panel);

		courseListTable = new JTable();
		courseListTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent me) {
				selectedCourse(me);
			}
		});
		courseListTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
		courseListTable.setModel(new DefaultTableModel(new Object[][] {},
				new String[] { "\u8BFE\u7A0B\u7F16\u53F7", "\u8BFE\u7A0B\u540D\u79F0", "\u6388\u8BFE\u6559\u5E08",
						"\u8BFE\u7A0B\u6700\u5927\u4EBA\u6570", "\u5DF2\u9009\u4EBA\u6570",
						"\u8BFE\u7A0B\u4ECB\u7ECD" }) {
			boolean[] columnEditables = new boolean[] { false, true, false, false, false, false };

			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		courseListTable.getColumnModel().getColumn(3).setPreferredWidth(106);
		courseListTable.getColumnModel().getColumn(5).setPreferredWidth(204);
		scrollPane.setViewportView(courseListTable);
		getContentPane().setLayout(groupLayout);
		setTeacherCombox();
		setCourseListTable(new Course());
		initTable();
		setAuthority();
	}

	protected void editCourseSubmit(ActionEvent ae) {
		// TODO 自动生成的方法存根
		int row = courseListTable.getSelectedRow();
		if (row == -1) {
			JOptionPane.showMessageDialog(this, "请选中要修改的数据!");
			return;
		}
		int course_id = Integer.parseInt(courseListTable.getValueAt(row, 0).toString());
		Teacher teacher = (Teacher) editCourseTeachComboBox.getSelectedItem();
		String courseName = editCourseTextField.getText().toString();
		if (StringUtil.isEmpty(courseName)) {
			JOptionPane.showMessageDialog(this, "课程名称不能为空!");
			return;
		}
		int max_student_num = 0;
		try {
			max_student_num = Integer.parseInt(editCourseStudentNumTextField.getText().toString());
		} catch (Exception e) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(this, "请选输入大于0的整数!");
			return;
		}
		String courseInfo = editCourseInfoTextArea.getText().toString();
		Course course = new Course();
		course.setId(course_id);
		course.setName(courseName);
		course.setTeacher_id(teacher.getId());
		course.setMax_student_num(max_student_num);
		course.setInfo(courseInfo);
		CourseDao courseDao = new CourseDao();
		if (courseDao.update(course)) {
			JOptionPane.showMessageDialog(this, "修改成功!");
		} else {
			JOptionPane.showMessageDialog(this, "修改失败!");
		}
		courseDao.closeDao();
		if ("教师".equals(MainFrm.userType.getName())) {
			Teacher teachers = (Teacher) searchTeacherComboBox.getSelectedItem();
			Course c = new Course();
			c.setTeacher_id(teachers.getId());
			setCourseListTable(c);
		} else {
			setCourseListTable(new Course());
		}
	}

	protected void selectedCourse(MouseEvent me) {
		// TODO 自动生成的方法存根
		int row = courseListTable.getSelectedRow();
		String courseName = courseListTable.getValueAt(row, 1).toString();
		int teacher_id = getTeacherIdByName(courseListTable.getValueAt(row, 2).toString());
		int max_student_num = Integer.parseInt(courseListTable.getValueAt(row, 3).toString());
		String courseInfo = courseListTable.getValueAt(row, 5).toString();
		editCourseTextField.setText(courseName);
		editCourseStudentNumTextField.setText(max_student_num + "");
		editCourseInfoTextArea.setText(courseInfo);
		for (int i = 0; i < editCourseTeachComboBox.getItemCount(); i++) {
			Teacher t = (Teacher) editCourseTeachComboBox.getItemAt(i);
			if (t.getId() == teacher_id) {
				editCourseTeachComboBox.setSelectedIndex(i);
				break;
			}
		}
	}

	protected void searchCourse(ActionEvent ae) {
		// TODO 自动生成的方法存根
		String searchCourseName = searchCourseNameTextField.getText().toString();
		Teacher teacher = (Teacher) searchTeacherComboBox.getSelectedItem();
		Course course = new Course();
		course.setName(searchCourseName);
		course.setTeacher_id(teacher.getId());
		setCourseListTable(course);
	}

	protected void deleteCourse(ActionEvent ae) {
		// TODO 自动生成的方法存根
		int row = courseListTable.getSelectedRow();
		if (row == -1) {
			JOptionPane.showMessageDialog(this, "请选中要删除的数据!");
			return;
		}
		int course_id = Integer.parseInt(courseListTable.getValueAt(row, 0).toString());
		CourseDao courseDao = new CourseDao();
		if (courseDao.delete(course_id)) {
			JOptionPane.showMessageDialog(this, "删除成功!");
		} else {
			JOptionPane.showMessageDialog(this, "删除失败!");
		}
		courseDao.closeDao();
		setCourseListTable(new Course());
	}

	private void setCourseListTable(Course course) {
		CourseDao courseDao = new CourseDao();
		List<Course> courseList = courseDao.getCourseList(course);
		DefaultTableModel dft = (DefaultTableModel) courseListTable.getModel();
		dft.setRowCount(0);
		for (Course c : courseList) {
			Vector v = new Vector();
			v.add(c.getId());
			v.add(c.getName());
			v.add(getTeacherNameById(c.getTeacher_id()));
			v.add(c.getMax_student_num());
			v.add(c.getSelected_num());
			v.add(c.getInfo());
			dft.addRow(v);
		}
		courseDao.closeDao();
	}

	private void setTeacherCombox() {
		// TODO 自动生成的方法存根
		TeacherDao teacherDao = new TeacherDao();
		teacherList = teacherDao.getTeacherList(new Teacher());
		teacherDao.closeDao();
		for (Teacher teacher : teacherList) {
			editCourseTeachComboBox.addItem(teacher);
			searchTeacherComboBox.addItem(teacher);
		}
		if ("教师".equals(MainFrm.userType.getName())) {
			Teacher user = (Teacher) MainFrm.userObject;
			for (int i = 0; i < searchTeacherComboBox.getItemCount(); i++) {
				Teacher teacher = (Teacher) searchTeacherComboBox.getItemAt(i);
				if (teacher.getId() == user.getId()) {
					searchTeacherComboBox.setSelectedIndex(i);
					editCourseTeachComboBox.setSelectedIndex(i);
					break;
				}
			}
		}
	}

	private String getTeacherNameById(int teacher_id) {
		String retString = "";
		for (Teacher teacher : teacherList) {
			if (teacher.getId() == teacher_id) {
				retString = teacher.getName();
				break;
			}
		}
		return retString;
	}

	private int getTeacherIdByName(String teacher_name) {
		int retId = -1;
		for (Teacher teacher : teacherList) {
			if (teacher_name.equals(teacher.getName())) {
				retId = teacher.getId();
				break;
			}
		}
		return retId;
	}

	private void setAuthority() {
		if ("教师".equals(MainFrm.userType.getName())) {
			deleteCourseButton.setEnabled(false);
			searchTeacherComboBox.setEnabled(false);
			editCourseTeachComboBox.setEnabled(false);
			editCourseTextField.setEnabled(false);
		}
	}

	private void initTable() {
		if ("教师".equals(MainFrm.userType.getName())) {
			Teacher teacher = (Teacher) searchTeacherComboBox.getSelectedItem();
			Course c = new Course();
			c.setTeacher_id(teacher.getId());
			setCourseListTable(c);
		}
	}
}
